package vars

import com.lesfurets.jenkins.unit.BasePipelineTest
import org.junit.Before
import org.junit.Test
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.constructor.SafeConstructor

import static org.assertj.core.api.Assertions.assertThat

class NotifyTest extends BasePipelineTest {
    @Override
    @Before
    void setUp() throws Exception {
        super.setUp()
    }

    @Test
    void canNotifyTest() throws Exception {
        def script = loadScript("vars/notifyUtil.groovy")
        assertThat((boolean) script.invokeMethod("canNotify", "Always", true)).isTrue()
        assertThat((boolean) script.invokeMethod("canNotify", "None", true)).isFalse()
        assertThat((boolean) script.invokeMethod("canNotify", "OnFailure", true)).isFalse()
        assertThat((boolean) script.invokeMethod("canNotify", "OnFailure", false)).isTrue()
    }

    @Test
    void notifyRepoTest() throws Exception {
        def script = loadScript("vars/notifyUtil.groovy")
        Object yaml = loadYaml()
        assertThat((boolean) script.invokeMethod("canBranchNotify", null, "master", true)).isFalse()
        assertThat((boolean) script.invokeMethod("canBranchNotify", null, "master", false)).isTrue()
        assertThat((boolean) script.invokeMethod("canBranchNotify", yaml.notify.repo, "master", true)).isTrue()
        assertThat((boolean) script.invokeMethod("canBranchNotify", yaml.notify.repo, "master", false)).isTrue()
        assertThat((boolean) script.invokeMethod("canBranchNotify", yaml.notify.repo, "online", true)).isFalse()
        assertThat((boolean) script.invokeMethod("canBranchNotify", yaml.notify.repo, "online", false)).isTrue()
        assertThat((boolean) script.invokeMethod("canBranchNotify", yaml.notify.repo, "dev", true)).isFalse()
        assertThat((boolean) script.invokeMethod("canBranchNotify", yaml.notify.repo, "dev", false)).isFalse()
        assertThat((boolean) script.invokeMethod("canBranchNotify", yaml.notify.repo, "feature", true)).isFalse()
        assertThat((boolean) script.invokeMethod("canBranchNotify", yaml.notify.repo, "feature", false)).isTrue()
    }

    /**
     * 采用和 pipeline-utility-steps-plugin 一样的 yaml 读取库
     * @return
     */
    Object loadYaml() {
        return new Yaml(new SafeConstructor()).loadAll("""
notify:
  wechatHook: https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXXX
  diff: None
  repo:
    master: Always
    online: OnFailure
    dev: None
""").getAt(0)
    }
}
